package person.csx.meeting.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import person.csx.meeting.model.Department;
import person.csx.meeting.model.Employee;
import person.csx.meeting.service.DepartmentService;
import person.csx.meeting.service.EmployeeService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DepartmentService departmentService;

    @RequestMapping("/")
    public String login() {

        return "login";
    }

    @PostMapping("/dologin")
    public String doLogin(Model model, String username, String password, HttpSession session) {
        Employee employee = employeeService.doLogin(username, password);
        if (employee == null) {
            model.addAttribute("error", "用户名或密码错误，登陆失败！");
            return "forward:/";
        } else {
            if ("0".equals(employee.getStatus())) {
                model.addAttribute("error", "用户待审批！");
                return "forward:/";
            } else if ("2".equals(employee.getStatus())) {
                model.addAttribute("error", "用户审批未通过！");
                return "forward:/";
            } else {
                session.setAttribute("currentuser", employee);
                return "redirect:/notifications";
            }
        }
    }


    @RequestMapping("/register")
    public String register(Model model) {
        List<Department> departments = departmentService.list();
        System.out.println(departments);
        model.addAttribute("departments", departments);
        return "register";
    }


    @RequestMapping("/doReg")
    public String doRegister(Employee employee, Model model) {
        Integer result = employeeService.doRegister(employee);
        if (result == 1) {
            return "redirect:/";
        } else {
            model.addAttribute("error", "注册失败");
            model.addAttribute("employee", employee);
            return "forward:/register";
        }
    }
}
